package cn.hp.controller;
import cn.hp.common.constant.Constants;
import cn.hp.entity.Department;
import cn.hp.service.DepartmentService;
import cn.hp.util.RandomNumber;
import cn.hp.util.RedisUtil;
import cn.hp.util.Result;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/api/department")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;
    @Resource
    private RedisUtil redisUtil;
    @GetMapping
    public Result find(Department department){
        if (!redisUtil.hasKey(Constants.DEPARTMENT_KEY)){
            List<Department> list =
                    departmentService.selectDepartment(department);
            redisUtil.set(Constants.DEPARTMENT_KEY, JSON.toJSONString(list),
                    RandomNumber.randomNum(null));
        }
        Object obj = redisUtil.get(Constants.DEPARTMENT_KEY);
        List<Department> departments = JSON.parseArray((String)obj,
                Department.class);
        return Result.success(departments);
    }
    @RequestMapping("/page")
    public Result page(Department department, @RequestParam(value = "page",
            defaultValue = "1") Integer page,@RequestParam(value = "limit", defaultValue =
            "10") Integer limit){
        PageInfo<Department> pageInfo =
                departmentService.selectDepartment(department, page, limit);
        return Result.success(pageInfo);
    }
    @PostMapping
    public Result insert(@RequestBody Department department){
        redisUtil.del(Constants.DEPARTMENT_KEY);
        int i = departmentService.insertDepartment(department);
        return i > 0 ? Result.success("新增成功") : Result.error("新增失败");
    }
    @PutMapping
    public Result update(@RequestBody Department department) {
        redisUtil.del(Constants.DEPARTMENT_KEY);
        int i = departmentService.updateDepartment(department);
        return i > 0 ? Result.success("修改成功") : Result.error("修改失败");
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        redisUtil.del(Constants.DEPARTMENT_KEY);
        int i = departmentService.deleteDepartmentById(id);
        return i > 0 ? Result.success("删除成功") : Result.error("删除失败");
    }
}